﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;



public partial class UnAssignFromAR : System.Web.UI.Page
{


    public List<Persons> mlstPersons
    {
        get
        {
            if (ViewState["mlstPersons"] == null)
                ViewState["mlstPersons"] = System.Guid.NewGuid().ToString();

            if (Session[ViewState["mlstPersons"].ToString()] == null)
                Session[ViewState["mlstPersons"].ToString()] = new List<Persons> ();

            return Session[ViewState["mlstPersons"].ToString()] as List<Persons>;
        }
        set
        {
            if (ViewState["mlstPersons"] == null)
                ViewState["mlstPersons"] = System.Guid.NewGuid().ToString();
            Session[ViewState["mlstPersons"].ToString()] = value;
        }
    }



    public List<Persons> mlstReqPersons
    {
        get
        {
            if (ViewState["mlstReqPersons"] == null)
                ViewState["mlstReqPersons"] = System.Guid.NewGuid().ToString();

            if (Session[ViewState["mlstReqPersons"].ToString()] == null)
                Session[ViewState["mlstReqPersons"].ToString()] = new List<Persons>();

            return Session[ViewState["mlstReqPersons"].ToString()] as List<Persons>;
        }

        set
        {
            if (ViewState["mlstReqPersons"] == null)
                ViewState["mlstReqPersons"] = System.Guid.NewGuid().ToString();

            
            Session[ViewState["mlstReqPersons"].ToString()]  = value;
        }
       
    }


    public Persons mobjUser
    {
        get
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();

            if (Session[ViewState["mobjUser"].ToString()] == null)
                Session[ViewState["mobjUser"].ToString()] = new Persons();

            return Session[ViewState["mobjUser"].ToString()] as Persons;
        }
        set
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mobjUser"].ToString()] = value;
        }
        
    }


    public Persons mobjManager
    {
        get
        {
            if (ViewState["mobjManager"] == null)
                ViewState["mobjManager"] = System.Guid.NewGuid().ToString();

            if (Session[ViewState["mobjManager"].ToString()] == null)
                Session[ViewState["mobjManager"].ToString()] = new Persons();

            return Session[ViewState["mobjManager"].ToString()] as Persons;
        }
        set
        {
            if (ViewState["mobjManager"] == null)
                ViewState["mobjManager"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mobjManager"].ToString()] = value;
        }

    }




    protected void Page_Load(object sender, EventArgs e)
    {
        
        if (!Page.IsPostBack)
        {
            mobjUser = GlobalVars.getCurrentPersonAR();
            checkSecurityAndCustomizePage(mobjUser);
            bindGrid("");
            
        }




    }


    /// <summary>
    /// this function will bind the persons grid due to a search text
    /// </summary>
    /// <param name="strSearch">the text to search for</param>
    private void bindGrid(string strSearch)
    {

        mlstPersons = search(strSearch);

        grdUsers.DataSource = mlstPersons;
        grdUsers.DataBind();


        grdEmployees.DataSource = new List<Persons>();
        grdEmployees.DataBind();
    }


   


    /// <summary>
    /// this function will check the security and if not found it will redirect
    /// </summary>
    /// <param name="mobjUser">the user to check its priveleges</param>
    private void checkSecurityAndCustomizePage(Persons mobjUser)
    {
        if ((!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Manager_page)) && mobjUser.lstAddEmployees.Count == 0 )
        {
            Response.Redirect("LoginAR.aspx");
        }
    }




    /// <summary>
    /// this function will search in Persons and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of Persons  matched</returns>
    public static List<Persons> search(string txtText)
    {

        PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);
        List<Persons> lstRet = new List<Persons>();

        if (txtText.Trim() == "")
        {
            List<Persons> lstNew = objPersonsDB.Select(" top 100 ", " order by [Name_AR] ");
            //lstNew = new List<Persons>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            return lstNew;
        }


        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }



        foreach (string strValue in strValues)
        {
            Persons objPersons = new Persons();
            objPersons.Badge = objPersons.ID = objPersons.FamilyName_AR = objPersons.FamilyName_EN = objPersons.Name_AR = objPersons.Name_EN =
                objPersons.MiddleName_AR = objPersons.MiddleName_EN = "%" + strValue + "%";

            List<Persons> lstPersons = objPersonsDB.SearchLikeOROrderByNAME_EN(objPersons);
            //lstPersons = new List<Persons>(from objFol in lstPersons where objFol.StatusID != 2 select objFol);

            foreach (Persons objFol in lstPersons)
            {
                if ((from objIn in lstRet where objIn.GenID == objFol.GenID select objIn).ToList().Count == 0)
                {
                    lstRet.Add(objFol);
                }
            }

        }


        return lstRet;



    }


    protected void grdUsers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        long PersonID = long.Parse( grdUsers.DataKeys[e.NewEditIndex]["GenID"].ToString());

        PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);

        List<Persons> lstFound = objPersonsDB.getPersonsByGenID(PersonID);

        if (lstFound.Count > 0)
        {
            


            mobjManager = lstFound[0];
            mlstReqPersons = lstFound[0].lstAddEmployees;


           

            mlstReqPersons = new List<Persons>(from obj in mlstReqPersons where mobjUser.lstAllEmployees.Contains(obj) select obj );
            
        }
        else
        {
            mobjManager = new Persons();
            mlstReqPersons = new List<Persons>();
            
        }

        bindEmployeesGrid();


        e.Cancel = true ;
    }



    /// <summary>
    /// this function will bind the employees grid
    /// </summary>
    private void bindEmployeesGrid()
    {
        grdEmployees.DataSource = mlstReqPersons;
        grdEmployees.DataBind();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        bindGrid(txtSearch.Text);
    }
    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = mlstPersons;
        grdUsers.PageIndex = e.NewPageIndex;
        grdUsers.DataBind();
    }

    //protected void grdCourses_RowDataBound(object sender, GridViewRowEventArgs e)
    //{
    //    if (e.Row.RowType == DataControlRowType.DataRow)
    //    {
    //        DropDownList ddlStatus = e.Row.FindControl("ddlStatus") as DropDownList;
            
    //        CourseStatusDB objCourseStatusDB = new CourseStatusDB (ConnectionStrings.LMS);
    //        List<CourseStatus> lstCourseStatus = objCourseStatusDB.Select("", "");

    //        ddlStatus.DataSource = lstCourseStatus;
    //        ddlStatus.DataTextField = "CourseStatusEN";
    //        ddlStatus.DataValueField = "ID";

    //        ddlStatus.DataBind();





    //        ddlStatus.SelectedValue = ((RegisteredCourses)e.Row.DataItem).CourseStatus.ToString();
            
    //    }
    //}

    protected void grdEmployees_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdEmployees.DataSource = mlstReqPersons;
        grdEmployees.PageIndex = e.NewPageIndex;
        grdEmployees.DataBind();
    }
    protected void btnDelegateSelected_Click(object sender, EventArgs e)
    {

        List<Persons> lstRemovedPersons = new List<Persons>();

        foreach (GridViewRow gvRow in grdEmployees.Rows)
        {
            if (gvRow.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkSelected = gvRow.FindControl("chkSelected") as CheckBox;

                if (chkSelected.Checked)
                {
                    long SelPersonID = long.Parse(grdEmployees.DataKeys[gvRow.RowIndex]["GenID"].ToString());

                    List<Persons> lstFound = new List<Persons>(from objEmp in mlstReqPersons where objEmp.GenID == SelPersonID select objEmp);

                    lstRemovedPersons.AddRange(lstFound);
                }
            }
        }


        if (lstRemovedPersons.Count == 0)
        {
            lblError.Text = "من فضلك اختر موظف واحد على الاقل لازالة صلاحيته من المدير.";
            return;
        }


        undelegateEmployees(mobjManager, lstRemovedPersons);

        updateEmployeesGrid();
       

    }



    public void updateEmployeesGrid()
    {
        PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);

        List<Persons> lstManagerFound = objPersonsDB.getPersonsByGenID(mobjManager.GenID);

        if (lstManagerFound.Count == 0)
        {
            grdEmployees.DataSource = new List<Persons>();
            grdEmployees.DataBind();
            return;
        }

        mobjManager = lstManagerFound[0];

        mlstReqPersons = mobjManager.lstAddEmployees;

        mlstReqPersons = new List<Persons>(from obj in mlstReqPersons where mobjUser.lstAllEmployees.Contains(obj) select obj);

        grdEmployees.DataSource = mlstReqPersons;
        grdEmployees.DataBind();
    }
    


    /// <summary>
    /// this function will un delegate the employees from a manager
    /// </summary>
    /// <param name="objManager">the manager to undelegate his employees</param>
    /// <param name="lstRemovedPersons">the employees to un delegate</param>
    private void undelegateEmployees(Persons objManager, List<Persons> lstRemovedPersons)
    {
        ManagerEmployeesDB objManagerEmployeesDB = new ManagerEmployeesDB(ConnectionStrings.LMS);

        List<ManagerEmployees> lstMe = new List<ManagerEmployees>(from obj in objManager.lstMyEmployeesManagerEmployees where (new List<Persons>(from newobj in lstRemovedPersons where newobj.GenID == obj.EmployeeID select newobj)).Count > 0 select obj);

        foreach (ManagerEmployees obj in lstMe)
        {
            objManagerEmployeesDB.Delete(obj);
        }




        string strTitle = "تم ازالة صلاحيات بواسطتك";
        string strMessage = "لقد ازلت صلاحيات بعض الموظفين من المدير : " + mobjManager.getFullName() + " في نظام \"أنا أتعلم\" .";
        string MailAddress = mobjUser.Email;

        GlobalVars.SendRequestMail(strTitle, GlobalVars.buildMailBody(strMessage, true), MailAddress);


        strTitle = "تم ازالة صلاحيات منك";
        strMessage = "قام المدير : " + mobjUser.getFullName() + " بازالة صلاحيات بعض الموظفين منك في نظام \"أنا أتعلم\" .";
        MailAddress = mobjManager.Email;

        GlobalVars.SendRequestMail(strTitle, GlobalVars.buildMailBody(strMessage, true), MailAddress);
        

    }
    protected void btnDelegateAll_Click(object sender, EventArgs e)
    {
        mlstReqPersons = mobjManager.lstAddEmployees;

        mlstReqPersons = new List<Persons>(from obj in mlstReqPersons where mobjUser.lstAllEmployees.Contains(obj) select obj);


        if (mlstReqPersons.Count == 0)
        {
            lblError.Text = "من فضلك اختر موظف واحد على الاقل لازالة صلاحيته من المدير.";
            return;
        }

        undelegateEmployees(mobjManager,mlstReqPersons);

        updateEmployeesGrid();
    }
}